package com.itheima.service.impl;

import com.itheima.mapper.DeptMapper;
import com.itheima.mapper.EmplMapper;
import com.itheima.pojo.Dept;
import com.itheima.pojo.DeptLog;
import com.itheima.service.DeptLogService;
import com.itheima.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class DeptServiceImpl implements DeptService {
    @Autowired
    private DeptMapper deptMapper;
    @Autowired
    private EmplMapper emplMapper;
    @Autowired
    private DeptLogService deptLogService;


    @Override
    public List<Dept> selectAllDepts() {
//  返回的数据没有必要用变量接收
//        List<Dept> deptList=deptMapper.sellectAllDepts();
//        return deptList;
        return deptMapper.sellectAllDepts();
    }
    /*
    事务管理,多次增删改操作,操作不能统一执行成功,通过@Transactional开启事务
        rollbackFor属性控制出现何种异常,回滚事务,默认是RuntimeException
        propagation属性控制事务的传播行为:
            REQUIRED:需要事务,有就加入,没有就创建新事物
            REQUIRES_NEW:需要事务,总是创建新事物,挂起旧事务
     */
    @Transactional(rollbackFor =Exception.class ,propagation = Propagation.REQUIRED)
    @Override
    public void deleteDeptById(Integer id) {
        try {
            deptMapper.deleteDeptById(id);
            int i=1/0;
            emplMapper.deleteByDeptId(id);

        } finally {
            DeptLog deptLog=new DeptLog();
            deptLog.setCreateTime(LocalDateTime.now());
            deptLog.setDescription("执行解散部门操作,解散"+id+"号部门");
            deptLogService.insert(deptLog);
        }
    }

    @Override
    public void addDept(Dept dept) {
        dept.setCreateTime(LocalDateTime.now());
        dept.setUpdateTime(LocalDateTime.now());
        deptMapper.addDept(dept);

    }

    @Override
    public Dept selectDeptById(Integer id) {
        return deptMapper.selectDeptById(id);
    }

    @Override
    public void updateDept(Dept dept) {
        dept.setUpdateTime(LocalDateTime.now());
        deptMapper.updateDept(dept);
    }
}
